import dayjs from 'dayjs'
import { HOUR_SECOND, MIN_SECOND, DAY_SECOND } from '../constants'

type Option = {
    format?: string
}

export const formatTimestamp = (timestamp: number, format = 'YYYY-MM-DD HH:mm') => {
    return dayjs(timestamp).format(format)
}

export const formatSecond = (s: number, unit = true): string => {
    const second = Math.floor(s);
    if (unit === true) {
        const hour = Math.floor(second / HOUR_SECOND);
        const min = Math.floor((second - hour * HOUR_SECOND) / MIN_SECOND);
        const s = second % MIN_SECOND

        const formattedTime = `${hour.toString().padStart(2, '0')}h:${min.toString().padStart(2, '0')}m:${s.toString().padStart(2, '0')}s`;
        return formattedTime
    }

    return secondsToHHMMSS(second)
}


/**
 * 格式化倒计时
 * @param millisecond
 * @param option 
 */
export const formatCountDown = (millisecond: number, option?: Option): string => {
    return formatSecondCountDown(Math.floor(millisecond / 1000), option)
}
/**
 * 格式化倒计时
 * @param millisecond
 * @param option 
 */
export const formatSecondCountDown = (second: number, option?: Option): string => {
    const format = option?.format || 'HH:mm:ss'
    let res = format

    let day = 0
    let hour = 0
    let min = 0
    let s = 0
    let leftSecond = second < 0 ? 0 : second

    const replace = (origin: string, check: string, value: () => number) => {
        const idx = format.indexOf(check)
        if (idx !== -1) {
            return origin.replace(check, value().toString().padStart(2, '0'))
        }
        return origin
    }

    res = replace(res, 'DD', () => {
        day = Math.floor(leftSecond / DAY_SECOND)
        leftSecond = leftSecond - day * DAY_SECOND
        return day
    })

    res = replace(res, 'HH', () => {
        hour = Math.floor(leftSecond / HOUR_SECOND)
        leftSecond = leftSecond - hour * HOUR_SECOND
        return hour
    })

    res = replace(res, 'mm', () => {
        min = Math.floor(leftSecond / MIN_SECOND)
        leftSecond = leftSecond - min * MIN_SECOND
        return min
    })

    res = replace(res, 'ss', () => {
        s = Math.floor(leftSecond)
        return s
    })
    return res

}

export const formatMillisecond = (millisecond: number, unit = true): string => {
    return formatSecond(millisecond / 1000, unit);
}

export const millsToHHMMSS = (mills: number) => {
    const date = new Date(mills);
    const formattedTime = date.toISOString().substring(11, 19);
    return formattedTime;
}

export const secondsToHHMMSS = (seconds: number) => {
    return millsToHHMMSS(seconds * 1000);
}


